package com.idlecode.service;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: IdleCode
 * @description 缓存代码格式配置信息
 * @author: rongjuwei
 * @create: 2024-02-06 09:37
 **/
@Service
@State(name = "IdleCodeTool", storages = @Storage(value = "IdleCodeTool.xml"))
public final class ToolService implements PersistentStateComponent<ToolService> {

    private Map<String, String> smMap = new HashMap<>(); // 初始化为空的 HashMap

    public static ToolService getInstance() {
        return ApplicationManager.getApplication().getService(ToolService.class);
    }

    /**
     * 持久化配置
     */
    @Override
    public ToolService getState() {
        return this;
    }

    /**
     * 加载配置
     */
    @Override
    public void loadState(@NotNull ToolService state) {
        this.smMap = state.smMap != null ? state.smMap : new HashMap<>();
    }

    /**
     * 找不到配置文件时加载
     */
    @Override
    public void noStateLoaded() {
        System.out.println("找不到配置文件");
        smMap = new HashMap<>();
    }

    public String getValue(String key) {
        return smMap.get(key);
    }

    public void put(String key, String value) {
        this.smMap.put(key, value);

        // 直接调用持久化组件保存当前状态
        ApplicationManager.getApplication().invokeLater(() -> {
            ToolService service = ToolService.getInstance();
            ApplicationManager.getApplication().getService(PersistentStateComponent.class).loadState(service.getState());
        });
    }

    public Map<String, String> getSmMap() {
        return smMap;
    }

    public void setSmMap(Map<String, String> smMap) {
        this.smMap = smMap;
    }
}